package com.swsc.xapp.offline;

import android.os.AsyncTask;
import android.widget.Toast;

import com.swsc.xapp.utils.ContextUtils;
import com.swsc.xapp.xroom.OfflineUploadService;

public class UploadTask extends AsyncTask<String, Integer, Integer> {

    public static final int TYPE_SUCCESS = 0;
    public static final int TYPE_FAILED = 1;
    public static final int TYPE_PAUSED = 2;
    public static final int TYPE_CANCELED = 3;

    private UploadListener listener;

    private boolean isCanceled = false;

    private boolean isPaused = false;

    private int lastProgress;

    public UploadTask(UploadListener listener) {
        this.listener = listener;
    }

    @Override
    protected Integer doInBackground(String... params) {
        String organNo = params[0];
        if(null == organNo){
            Toast.makeText(ContextUtils.getCurApplication(), "未指定电站", Toast.LENGTH_SHORT).show();
            return TYPE_FAILED;
        }
        Long userNo = Long.parseLong(organNo);
        return upload((int) (userNo / 1000));
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        int progress = values[0];
        if (progress > lastProgress) {
            listener.onProgress(progress);
            lastProgress = progress;
        }
    }

    @Override
    protected void onPostExecute(Integer integer) {
        switch (integer) {
            case TYPE_SUCCESS:
                listener.onSuccess();
                break;
            case TYPE_FAILED:
                listener.onFailed();
                break;
            case TYPE_PAUSED:
                listener.onPaused();
                break;
            case TYPE_CANCELED:
                listener.onCanceled();
                break;
            default:
                break;
        }
    }

    public void pauseUpload() {
        isPaused = true;
    }

    public void cancelUpload() {
        isCanceled = true;
    }

    private Integer upload(Integer organNo) {
        if (null == organNo) {
            return TYPE_FAILED;
        }
        OfflineUploadService.getInstance().uploadChange();
        publishProgress(50);
        OfflineUploadService.getInstance().uploadNew();
        publishProgress(100);
        return TYPE_SUCCESS;
    }
}
